#!/usr/bin/perl
#
# Display info about a Person, with the option to
# edit, and to push lots of buttons to do things with his Place.
#
use LinuxCounter;
use FileTable;
use Fcntl;
use Counter::CGI;
use ErrorForm;
use CounterCGI;
use Validate::Places;
use Validate::Persons;
use Counter;

$] > 5.008 && binmode(STDOUT, ":utf8"); # set web page output to utf-8
$testmode = 0;

$q = new Counter::CGI;
$users = Counter::open(O_RDWR);
$k1 = $q->param("key");
$k2 = $q->param("key2");

if ($k1 > $k2) {
    my $kt = $k1;
    $k1 = $k2;
    $k2 = $kt;
}
if ($k1 == $k2) {
    errorForm(__("The records are the same"));
}


$r1 = $users->get($k1);
$r2 = $users->get($k2);
if (!$r1 || !$r2) {
    errorForm(__("Record not found"));
}

print <<EoF;
Content-type: text/html; charset="utf-8"

EoF
print "<html>\n<head>\n<title>", __("Merging"), " $k1 $k2</title>\n";
print "</head><body bgcolor=\"white\">";
print "<h1>", __("Merging"), " $k1 " , __("and"), " $k2</h1>\n";
print "\n<pre>\n";

print "R1: $$r1{email}\n";
print __("Machines"), ": ", $r1->machines() + 0, "\n";
print __("Emails"), ": ", $r1->emails() + 0, "\n";
print __("Friends"), ": ", $r1->friends() + 0, "\n";
print __("Records"), ": ", $r1->ownedrecs() + 0, "\n";

print "R2: $$r2{email}\n";
print __("Machines"), ": ", $r2->machines() + 0, "\n";
print __("Emails"), ": ", $r2->emails() + 0, "\n";
print __("Friends"), ": ", $r2->friends() + 0, "\n";
print __("Records"), ": ", $r2->ownedrecs() + 0, "\n";

movesubrecs();


mergerecs($r1->person(O_CREAT), $r2->person(), "person");
mergerecs($r1, $r2, "user");

print "\n<hr>\n";
print "<a href=\"/adm/\">", __("Back to admin page"), "</a>\n";
print <<EoF;
</body>
</html>
EoF


sub movesubrecs {
    my $subrec;

    for $subrec ($r2->ownedrecs()) {
	$subrec->{owner} = $r1->key();
	$subrec->store() if !$testmode;
    }
}

sub mergerecs {
    my $p1 = shift;
    my $p2 = shift;
    my $what = shift;
    my $field;
    my $changes;

    return if !$p2;
    die "Cannot merge to empty\n" if !$p1;
    for $field ($p2->fields()) {
	if ($p1->{$field} && $p2->{$field} ne $p1->{$field}) {
	    print __("Difference"), " $what $field: p1 $$p1{$field} p2 $$p2{$field}\n";
	} elsif (!$p1->{$field}) {
	    print __("Adding to"), " p1 $what: $field: $$p2{$field}\n";
	    $p1->{$field} = $p2->{$field};
	    ++ $changes;
	}
    }
    $p1->store() if $changes && !$testmode;
    $p2->delete() if !$testmode;
}
